# -*- coding: utf-8 -*-
import smtplib
import sys
from smtplib import email
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email.Encoders import encode_base64
import os
import mimetypes
import time, datetime
import re
from pymongo import Connection

### GMAIL USER FOR SEND MAIL ###
gmail_user = "mana.notification@gmail.com"
gmail_pwd = "@mana^^log**??"
################################
tomail = ["hai@mana.vn", "giangnh@mana.vn"]

NOW = datetime.datetime.now()
file_dir = "/home/hoangnamhai/sendmail-config.txt"

if not os.path.isfile(file_dir):
    if not os.path.isdir(os.path.dirname(file_dir)):
        os.mkdir(os.path.dirname(file_dir))
    f = file(file_dir, 'r+')
    f.close()

connection = Connection('localhost', 27017)
db = connection["mongolog"]
collection = db["log"]

numberOfErrorPerEmail = 50

### SEND MAIL ##################
def attachFile(attachmentPath):
    contentType, encoding = mimetypes.guess_type(attachmentPath)
    if contentType is None or encoding is None:
        contentType = "application/octet-stream"
    cType, subType = contentType.split("/", 1)
    
    file = open(attachmentPath, 'rb')
    if cType == 'image':
        attachment = MIMEImage(file.read(), _subtype=subType)
    else:
        attachment = MIMEBase('application', 'octet-stream')
        attachment.set_payload(file.read())
        encode_base64(attachment)
    attachment.add_header('Content-Disposition',
                    'attachment; filename="%s"' % os.path.basename(attachmentPath))
    return attachment
    
def mail(to, subject, body, attach=False, pathArr=None):
    msg = MIMEMultipart()

    msg['From'] = gmail_user
    msg['To'] = to
    msg['Subject'] = subject

    msg.attach(MIMEText(body))
    if attach:
        for pathOfFile in pathArr:
            if os.path.isfile(pathOfFile):
                msg.attach(attachFile(pathOfFile))
    
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmail_user, gmail_pwd)
    mailServer.sendmail(gmail_user, to, msg.as_string())
    mailServer.close()

def sendMail(to, subject, body):
    for amail in to:
        mail(amail, subject, body)


############################################

currentHour = datetime.datetime.today().hour



        
subject = "Logging notification: " + str(datetime.datetime.now())
#mail("51pm1@it-uce.com", subject, "hoi tham cac chu", True, ['D:/LHGiang/Projects/crawler/src/smtp.py', 'D:/LHGiang/Projects/crawler/src/CafeF_LichThiTruong.py'])
f = open(file_dir, 'r+')
lastTime = f.readline().strip()
status = f.readline().strip()
if currentHour < 23 and currentHour != 0:
    status = "Reported: False" 
f.close()
today = datetime.datetime.today()
startOfDay = datetime.datetime(today.year, today.month, today.day)

if re.search(r"\d+-\d+-\d+\s\d+:\d+:\d+\.\d+", lastTime):
    lastTime = datetime.datetime.strptime(lastTime, "%Y-%m-%d %H:%M:%S.%f")    
else:
    lastTime = startOfDay
criticalArr = []
errorArr = []
iCount = 1
for row in collection.find({"time": {"$gte": lastTime}}):
    if iCount > numberOfErrorPerEmail: break
    if row['level'] == 'critical':
        strErr = "\nTime: {0}\tName: {1}\tFunction: {2}\nMessage: {3}".format(row['time'], row['name'], row['funcname'], row['msg'])
        errorArr.append(strErr)
        iCount += 1
    if row['level'] == 'error':
        strErr = "\nTime: {0}\tName: {1}\tFunction: {2}\nMessage: {3}".format(row['time'], row['name'], row['funcname'], row['msg'])
        criticalArr.append(strErr)
        iCount += 1

msg = ""
if len(errorArr)>0:
    msg += "\n============================\n"
    msg += "Tong so error: {0}".format(len(errorArr))
    for line in errorArr:
        msg += line +"\n"
if len(criticalArr)>0:
    msg += "\n============================\n"
    msg += "Tong so critical: {0}".format(len(criticalArr))
    for line in criticalArr:
        msg += line +"\n"
#print msg
if msg != '':
    sendMail(["giangnh@mana.vn"], subject, msg)

if currentHour == 23 or currentHour == 0:
    print currentHour
    if status == "Reported: False":
        status = "Reported: True"
        warnArr = []
        iCount = 0
        for row in collection.find({"time": {"$gte": startOfDay}}):
            if iCount > numberOfErrorPerEmail: break
            print row['level']
            if row['level'] == 'warning':
                strErr = "\nTime: {0}\tName: {1}\tFunction: {2}\nMessage: {3}".format(row['time'], row['name'], row['funcname'], row['msg'])
                warnArr.append(strErr)
                iCount += 1
        
        print warnArr
        
        msg = ""
        if len(warnArr)>0:
            msg += "\n============================\n"
            msg += "Tong so warning: {0}".format(len(warnArr))
            for line in warnArr:
                msg += line +"\n"
        subject = "Logging notification report" + str(datetime.datetime.now())
        if msg != '':
            sendMail(["giangnh@mana.vn"], subject, msg)

timeLog = str(datetime.datetime.now())+"\n"+status
f = open(file_dir, 'w')
f.write(timeLog)
f.close()

print "\n\nFinished"
sys.exit()

